﻿using UnityEngine;
using System.Collections.Generic;
using UnityEngine.UI;

[RequireComponent(typeof(UnityEngine.UI.LoopScrollRect))]
[DisallowMultipleComponent]
public class HistoryScroll : MonoBehaviour, LoopScrollPrefabSource, LoopScrollDataSource
{
    public GameObject item;
    public int        totalCount = -1; //若为负数则为无限循环列表

    Stack<Transform> pool = new Stack<Transform>();

    void Start()
    {
        var ls = GetComponent<LoopScrollRect>();
        ls.prefabSource = this;
        ls.dataSource   = this;
        ls.totalCount   = LocalConfig.intance.scoreList.Count;
        Debug.Log(LocalConfig.intance.scoreList.Count);
        ls.RefillCells(); //初始化并填满元素
        
    }

    //实现LoopScrollDataSource接口，子物体从这里拿到数据来刷新自身
    public void ProvideData(Transform transform, int idx)
    {
       transform.SendMessage("ScrollCellIndex", idx);
        
    }

    public GameObject GetObject(int index)
    {
        if (pool.Count == 0)
        {
            return Instantiate(item);
        }

        Transform candidate = pool.Pop();
        candidate.gameObject.SetActive(true);
        return candidate.gameObject;
    }

    public void ReturnObject(Transform trans)
    {
        // Use `DestroyImmediate` here if you don't need Pool
        trans.SendMessage("ScrollCellReturn", SendMessageOptions.DontRequireReceiver);
        trans.gameObject.SetActive(false);
        trans.SetParent(transform, false);
        pool.Push(trans);
    }
}